/*
 * © Copyright 2011 Romain Marteau, Matthieu Totet
 * 
 *    This file is part of VineaToum.
 *
 *    VineaToum is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    VineaToum is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with VineaToum.  If not, see <http://www.gnu.org/licenses/>.
 *    
 */

package org.vineatoum.view;

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.BorderLayout;

import javax.swing.JButton;

import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.JTabbedPane;
import javax.swing.JDesktopPane;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.JTree;
import javax.swing.JMenuBar;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import javax.swing.JMenu;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;

import org.vineatoum.business.Plantation;
import org.vineatoum.business.state.Benne;
import org.vineatoum.business.state.Marc;
import org.vineatoum.business.state.Mout;
import org.vineatoum.business.state.Vin;
import org.vineatoum.controller.IVineaToumController;
import org.vineatoum.controller.VineaToumController;
import org.vineatoum.model.VineaToumModel;
import org.vineatoum.model.abstraction.IVineaToumModel;
import org.vineatoum.utils.Calc;
import org.vineatoum.view.stateView.BenneActionPanel;
import org.vineatoum.view.stateView.MarcActionPanel;
import org.vineatoum.view.stateView.MoutActionPanel;
import org.vineatoum.view.stateView.PlantationActionPanel;
import org.vineatoum.view.stateView.VinActionPanel;
import org.vineatoum.view.utils.BusinessListTransfertHandler;
import org.vineatoum.view.utils.BusinessPanelFactory;
import org.vineatoum.view.utils.JPanelWrapperOkCancel;
import org.vineatoum.view.utils.TransferableBusinessAbstract;
import org.vineatoum.view.utils.TransferableVinAbstract;

import javax.swing.ImageIcon;

import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainWindow extends JFrame  {
	private static final long serialVersionUID = 5384905490995860728L;
	private JFrame frmVineatoum;
	private IVineaToumModel model;
	private IVineaToumController controller;
	private Calc calcGui = new Calc();// Finally we instantiate the CalcGui
	
	private JTabbedPane tabbedPane;

	
	// FIXME model autowired when persistance and spring

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainWindow window = new MainWindow(new VineaToumModel());
					window.frmVineatoum.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 * @param vineaToumModel 
	 */
	public MainWindow(VineaToumModel vineaToumModel) {		
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");	        
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		model = vineaToumModel;
		controller = new VineaToumController(model);

		initialize();
	}

	/**	
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmVineatoum = new JFrame();
		frmVineatoum.setTitle("VineaToum");
		frmVineatoum.setBounds(100, 100, 923, 525);
		frmVineatoum.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JMenuBar menuBar = new JMenuBar();
		frmVineatoum.getContentPane().add(menuBar, BorderLayout.NORTH);
		
		calcGui.setVisible(true);
        calcGui.setVisible(false);
		// class/
        calcGui.setSize(300, 300); // here we define the size of our frame.
        
        calcGui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // set default
        calcGui.setLocation(600, 300);
		
        // close
        // operation
        // ....
        calcGui.setResizable(false); // setResizable(false) is used so that, our
		

		JMenu mnFichier = new JMenu("Fichier");
		menuBar.add(mnFichier);
		
		JMenu mnEdition = new JMenu("Edition");
		menuBar.add(mnEdition);

		JMenu mnOutils = new JMenu("Outils");
		menuBar.add(mnOutils);
		
		JMenuItem mntmCalculatrice = new JMenuItem("Calculatrice");
		mntmCalculatrice.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				
				calcGui.setVisible(true); // here we make the interface visible
			}
		});
		mnOutils.add(mntmCalculatrice);
		
		JMenuItem mntmConvertisseur = new JMenuItem("Convertisseur");
		mntmConvertisseur.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				JOptionPane.showMessageDialog(frmVineatoum, 
						"Ici se trouvera un convertisseur. " +
							"Une quantité (en L) + une dose (en gramme) = concentration (en g/L) \n" +
							"Avec convertion possible des unités. (hL é la place de litre ; kg ou mg é la place de g ; etc...");
			}
		});
		mnOutils.add(mntmConvertisseur);
		
		JMenuItem mntmSugar = new JMenuItem("Calculateur de Sucre");
		mntmSugar.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				JOptionPane.showMessageDialog(frmVineatoum, 
						"Ici se trouvera un Calculateur pour ajouter du sucre dans le vin. \n" +
						"Champs é renseigner \n" +
						"Entrez le degré potentiel initial de votre vin avant enrichissement \n" +
						"Entrez le degré acquis final souhaité	 \n" +
						"Entrez le volume de moét é enrichir en hl \n" +
						
						"Quantité é rajouter pour atteindre le degré acquis souhaité");
				}
		});
		mnOutils.add(mntmSugar);
		
		JMenuItem mntmSO2 = new JMenuItem("Calculateur du SO2 actif");
		mntmSO2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				JOptionPane.showMessageDialog(frmVineatoum, 
						"Ici se trouvera un Calculateur pour calculer le SO2 actif du vin. \n" +
						"SO2 libre de votre vin (en mg/L)	\n" + 
						"pH de votre vin	\n" +
						"TAV de votre vin (en %)\n" +	
						"Température de votre vin (en éC)\n" +
						"Donnera la quantité de SO2 actif du vin ainsi que les recommandations");
				}
		});
		mnOutils.add(mntmSO2);
		
		JMenu mnConfiguration = new JMenu("Configuration");
		menuBar.add(mnConfiguration);
		
		JMenu mnMesPlantations = new JMenu("Mes plantations");
		menuBar.add(mnMesPlantations);
		
		JMenu mnMonChai = new JMenu("Mon chai");
		menuBar.add(mnMonChai);
		
		JMenu mnMesVins = new JMenu("Mes vins");
		menuBar.add(mnMesVins);
		
		JMenu mnAide = new JMenu("Aide");
		menuBar.add(mnAide);

		JDesktopPane desktopPane = new JDesktopPane();
		frmVineatoum.getContentPane().add(desktopPane, BorderLayout.CENTER);
		desktopPane.setLayout(new BorderLayout(0, 0));

		JToolBar toolBarMode = new JToolBar();
		desktopPane.add(toolBarMode, BorderLayout.WEST);
		toolBarMode.setOrientation(SwingConstants.VERTICAL);

		JButton btnCuverie = new JButton("");
		btnCuverie.setIcon(new ImageIcon(getClass().getResource("/img/fut 48px.png")));
		toolBarMode.add(btnCuverie);

		JButton btnPlantation = new JButton("");
		btnPlantation.setIcon(new ImageIcon(getClass().getResource("/img/grapes 48px.png")));
		toolBarMode.add(btnPlantation);

		JButton btnExploitation = new JButton("");
		btnExploitation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				
				ExploitationPanel modelPanel = new ExploitationPanel(model,model.getExploitation());
				JPanelWrapperOkCancel exploitationPane = new JPanelWrapperOkCancel(modelPanel);
				
				tabbedPane.addTab("Exploitation", exploitationPane);
				tabbedPane.setSelectedComponent(exploitationPane);
				
				//TODO Keep a list to know the components present on the window
				//Also usefull to notify the correct view. Use a "double" pattern observer ? 
			}
		});
		btnExploitation.setToolTipText("Exploitation");
		btnExploitation.setIcon(new ImageIcon(getClass().getResource("/img/exploitation 48px.png")));
		toolBarMode.add(btnExploitation);
		
		JButton btnConfiguration = new JButton("");
		btnConfiguration.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				ConfigurationPanel modelPanel = new ConfigurationPanel(model);
				
				JPanelWrapperOkCancel configPane = new JPanelWrapperOkCancel(modelPanel);
				
				tabbedPane.addTab("Configuration", configPane);
				tabbedPane.setSelectedComponent(configPane);
				
				//TODO Keep a list to know the components present on the window
				//Also usefull to notify the correct view. Use a "double" pattern observer ? 
			}
		});
		btnConfiguration.setToolTipText("Configuration");
		btnConfiguration.setIcon(new ImageIcon(getClass().getResource("/img/config 48px.png")));
		toolBarMode.add(btnConfiguration);

		JToolBar toolBarActions = new JToolBar();
		desktopPane.add(toolBarActions, BorderLayout.NORTH);
		
		JButton button_1 = new JButton("");
		button_1.setIcon(new ImageIcon(getClass().getResource("/img/vendanger.jpg")));
		toolBarActions.add(button_1);
		
		JButton button = new JButton("");
		button.setIcon(new ImageIcon(getClass().getResource("/img/pressoir.jpg")));
		toolBarActions.add(button);
		
		JButton button1 = new JButton("");
		button1.setIcon(new ImageIcon(getClass().getResource("/img/analyse.jpg")));
		toolBarActions.add(button1);
		
		JButton button2 = new JButton("");
		button2.setIcon(new ImageIcon(getClass().getResource("/img/filtration.jpg")));
		toolBarActions.add(button2);
		
		JButton button3 = new JButton("");
		button3.setIcon(new ImageIcon(getClass().getResource("/img/degustation.jpg")));
		toolBarActions.add(button3);
		
		toolBarActions.addSeparator();
		
		JButton button_2 = new JButton("");
		button_2.setIcon(new ImageIcon(getClass().getResource("/img/import.png")));
		toolBarActions.add(button_2);
		
		JButton button_3 = new JButton("");
		button_3.setIcon(new ImageIcon(getClass().getResource("/img/export.png")));
		toolBarActions.add(button_3);
		
		JButton button_4 = new JButton("");
		button_4.setIcon(new ImageIcon(getClass().getResource("/img/search.png")));
		toolBarActions.add(button_4);
		
		toolBarActions.addSeparator();
		
		JButton button_5 = new JButton("");
		button_5.setIcon(new ImageIcon(getClass().getResource("/img/historique.gif")));
		toolBarActions.add(button_5);
		
		JSplitPane splitPane = new JSplitPane();
		desktopPane.add(splitPane, BorderLayout.CENTER);
		

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
	
		tabbedPane.setTransferHandler(new TransferHandler()
		{

			@Override
			public boolean canImport(TransferSupport support) {
				// TODO Auto-generated method stub
				
				return support.getTransferable().isDataFlavorSupported(TransferableBusinessAbstract.getNodeflavor())||support.getTransferable().isDataFlavorSupported(TransferableVinAbstract.getNodeflavor());
				//return support.isDataFlavorSupported(TransferableVinAbstract.nodeFlavor);
			}

			@Override
			public boolean importData(TransferSupport support) {
				if(canImport(support))
				{
					try {
						
						Object transferData = support.getTransferable().getTransferData(TransferableVinAbstract.getNodeflavor());
						
					
						tabbedPane.addTab(transferData.toString(), new JPanelWrapperOkCancel(BusinessPanelFactory.createBusinessPanel(model,transferData)));
						tabbedPane.setSelectedIndex(tabbedPane.getComponentCount()-1);
						
					} catch (UnsupportedFlavorException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
					
					return super.importData(support);
				}
				return false;
			}
			
		});
		
		
		splitPane.setRightComponent(tabbedPane);
		
//		ParcellePanel parcellePane = new ParcellePanel();
//		JPanelWrapper parcelleWrapper = new JPanelWrapper(parcellePane);
//		tabbedPane.addTab("Parcelle", parcelleWrapper);

//		PlantationPanel plantationPane = new PlantationPanel();
//		JPanelWrapper plantationWrapper = new JPanelWrapper(plantationPane);
//		tabbedPane.addTab("Plantation", plantationWrapper);

		JScrollPane scrollPane_1 = new JScrollPane();
		splitPane.setLeftComponent(scrollPane_1);

		JTree tree = new JTree();
		
		DefaultMutableTreeNode plantation = new DefaultMutableTreeNode("Plantation");
		
		DefaultMutableTreeNode Plantation1 = new DefaultMutableTreeNode(new Plantation("Plantation 1"));
		plantation.add(Plantation1);
		DefaultTreeModel treeModelExemple = new DefaultTreeModel(plantation);
		tree.setModel(treeModelExemple);
		
		
		tree.setTransferHandler(new BusinessListTransfertHandler());
		tree.setDragEnabled(true);
		scrollPane_1.setViewportView(tree);
		/*
		 * Plantation plantationA = new Plantation("Plantation A"); Plantation
		 * plantationB = new Plantation("Plantation B"); Plantation plantationC
		 * = new Plantation("Plantation C");
		 * 
		 * final String[] ids = new String[Plantation.getCollection().size()];
		 * int i = 0; for (Iterator iterator =
		 * Plantation.getCollection().iterator(); iterator.hasNext();) {
		 * Plantation p = (Plantation) iterator.next(); ids[i] = p.getId(); i++;
		 * }
		 * 
		 * final JList listPlantation = new JList(); listPlantation.setModel(new
		 * AbstractListModel() { String[] values = ids;
		 * 
		 * public int getSize() { return values.length; } public Object
		 * getElementAt(int index) { return values[index]; } });
		 * 
		 * listPlantation.addListSelectionListener(new ListSelectionListener() {
		 * 
		 * @Override public void valueChanged(ListSelectionEvent event) {
		 * System.
		 * out.println(listPlantation.getModel().getElementAt(event.getLastIndex
		 * ())); //frame.getContentPane().removeAll();
		 * frame.getContentPane().add(new PlantationPanel((String)
		 * listPlantation.getModel().getElementAt(event.getLastIndex())),
		 * BorderLayout.EAST); } });
		 * 
		 * 
		 * //listPlantation.set frame.getContentPane().add(listPlantation,
		 * BorderLayout.CENTER);
		 */
		
		JPanelWrapperOkCancel exploitationPane = new JPanelWrapperOkCancel(
				new PlantationActionPanel(model, Plantation.plantations.get(0)));
		tabbedPane.addTab("Plantation", exploitationPane);
		
		JPanelWrapperOkCancel bennePane = new JPanelWrapperOkCancel(
				new BenneActionPanel (model, Benne.bennes.get(0)));
		tabbedPane.addTab("Benne", bennePane);
		
		JPanelWrapperOkCancel moutPane = new JPanelWrapperOkCancel(
				new MoutActionPanel (model, new Mout()));
		tabbedPane.addTab("Mout", moutPane);
		
		JPanelWrapperOkCancel marcPane = new JPanelWrapperOkCancel(
				new MarcActionPanel (model, new Marc()));
		tabbedPane.addTab("Marc", marcPane);
		
		JPanelWrapperOkCancel vinPane = new JPanelWrapperOkCancel(
				new VinActionPanel (model, new Vin()));
		tabbedPane.addTab("Vin", vinPane);
		/*
		JPanelWrapperOkCancel liePane = new JPanelWrapperOkCancel(
				new LieActionPanel(model, new Lie()));
		tabbedPane.addTab("Lie", liePane);
		
		JPanelWrapperOkCancel lotPane = new JPanelWrapperOkCancel(
				new LotActionPanel(model, new Lot()));
		tabbedPane.addTab("Lot", lotPane);
		*/
	}
}
